package ink.metoo.auto.fishpi.chatroom.command

import ink.metoo.auto.fishpi.Log
import ink.metoo.auto.fishpi.call.ChatRoomCall
import ink.metoo.auto.fishpi.chatroom.Message
import org.apache.commons.lang3.math.NumberUtils
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.concurrent.timerTask

class SendRockPaperScissorsCommand : Command {

    companion object {
        private val timer = Timer()
        private var timerTask: TimerTask? = null

        fun cancelTimerTask() {
            timerTask?.cancel()
            timerTask = null
        }
    }

    override val commandText: String = "/猜拳"

    override fun isMatch(message: Message): Boolean {
        return super.isMatch(message) && message.isMe
    }

    override fun execute(message: Message) {
        if (timerTask != null) {
            cancelTimerTask()
        }
        val params = message.commandParams
        var maxSize = NumberUtils.toInt(params.getOrNull(1), 1).coerceAtLeast(1)
        val money = NumberUtils.toInt(params.getOrNull(2), 32).coerceAtLeast(32)
        val fms = maxSize
        val tt = timerTask {
            if (--maxSize < 0) {
                cancelTimerTask()
                return@timerTask
            }
            val result = ChatRoomCall.sendRedPacket {
                it.msg = params.getOrNull(3) ?: "来自拳皇的猜拳"
                it.money = money
                it.count = 1
                it.recivers = emptyList()
                it.type = "rockPaperScissors"
                it.gesture = (0..2).random().toString()
            }
            Log.debug("发送猜拳红包(${fms - maxSize}/${fms}), 发送结果: ${result.code == 0}")
        }
        timerTask = tt
        timer.schedule(tt, 0L, TimeUnit.SECONDS.toMillis(31L))
    }

}